//
//  MyAccountViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/28.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "MyAccountViewController.h"
#import "MyAccountView.h"
#import "MySelfTableViewCell.h"
#import "MoneyCardViewController.h"
#import "VeriftyViewController.h"
#import "AddBankCardViewController.h"
#import "PayViewController.h"
#import "DetailViewController.h"
#import "GetMoneyViewController.h"



@interface MyAccountViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)MyAccountView * myView;

@property (nonatomic, strong)UIView * cardView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)NSArray * imageNameArray;

@property (nonatomic, strong)NSArray * showStringArray;

@property (nonatomic, weak)UIImageView * topImageView;

@property (nonatomic, weak)UILabel * showLabel;

@property (nonatomic, weak)UIView * lineView;

@property (nonatomic, weak)UILabel * backLabel;

@property (nonatomic, weak)UIView * lineView2;

@property (nonatomic, weak)UILabel * sureLabel;

@property (nonatomic, copy)NSString * showViewString;

@property (nonatomic, copy)NSString * phoneString;

@property (nonatomic, strong)NSTimer * countDownTimer;

@end

@implementation MyAccountViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 2;


- (void)viewWillAppear:(BOOL)animated{

    
    [self loadData];
}


//- (void)viewDidDisappear:(BOOL)animated{

//     self.navigationController.navigationBar.barTintColor = ColorWithRGB(0x242424);
//    
//      self.navigationController.navigationBar.translucent = YES;
//    [self.navigationController.navigationBar setTranslucent:NO];
//}


- (void)loadData{
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    //user/balance
//    [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//        
//        NSDictionary * dict = responseObject[@"param"];
//        
//        NSDictionary * otherInfoDict = dict[@"otherInfo"];
////        NSDictionary * financeDict = dict[@"finance"];
//        
//        self.phoneString = otherInfoDict[@"phone"];
//        
////        NSString * str = financeDict[@"netAssets"];
//        
//        NSString * urlString = otherInfoDict[@"avatar"];
//        
////        self.myView.iconImageString = urlString;
//        if ([urlString isEqualToString:@""]) {
//            self.myView.userIconImageView.image = [UIImage imageNamed:@"默认头像"];
//        }else{
//            
//            self.myView.iconImageString = urlString;
//            
//        }
//        
//        NSString * nikeName = [NSString stringWithFormat:@"%@", otherInfoDict[@"nickname"]];
//        
//        if ([nikeName isEqualToString:@""]) {
//             self.myView.nameString = [NSString stringWithFormat:@"%@", otherInfoDict[@"phone"]];//otherInfoDict[@"nickname"];emailtring
//            
//        }else{
//           self.myView.nameString = nikeName;//otherInfoDict[@"nickname"];emailtring
//        }
//        
//        float total = [dict[@"balance"] floatValue];
//        
////        NSString * balanceString = [NSString stringWithFormat:@"%@", dict[@"balance"]];
////        float balance = [balanceString floatValue];
//        
////        self.myView.userMoneyString = [NSString stringWithFormat:@"$%.2f", balance];//dict[@"cashAvailable"];
//        
//        NSString * floatingProfitString = [NSString stringWithFormat:@"%@", dict[@"floatProfit"]];
//        
//        float floatingProfit = [floatingProfitString floatValue];
//        
//        self.myView.loseOrWinString = [NSString stringWithFormat:@"%.2f", floatingProfit];//dict[@"floatingProfit"];
//        
//        float netAssets = total + floatingProfit;
//        
//        float marginFree = [dict[@"marginFree"] floatValue];
//        
//        float userMoney = netAssets - marginFree;
//        
//        self.myView.userMoneyString = [NSString stringWithFormat:@"$%.2f", userMoney];
////        NSString * netAssetsString = [NSString stringWithFormat:@"%@", financeDict[@"netAssets"]];
////        float netAssets = [netAssetsString floatValue];
//        
//        if (netAssets == 0) {
//           self.myView.moneyString = @"$0.00";
//        }else{
//            self.myView.moneyString = [NSString stringWithFormat:@"$%.2f",netAssets];//dict[@"marginAvailable"];
//        }
//        
//        
////        NSLog(@"%@",dict);
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        [self.tableView reloadData];
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        NSLog(@"%@",error);
//        
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//    }];
//
//    
    [[NetworkTool sharedTools] POST:@"user/bank-list" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSDictionary * dict = responseObject[@"param"];
                
        if (dict.count == 0) {
            
            self.showViewString = @"show";
        }else{
            
            self.showViewString = @"hidden";
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    /*
     [userDefaults setObject:balanceFloatString forKey:@"balance"];
     [userDefaults setObject:floatProfitString forKey:@"floatProfit"];
     [userDefaults setObject:clearMoneyString forKey:@"clearMoney"];
     [userDefaults setObject:canUseMoneyString forKey:@"canUseMoney"];
     [userDefaults setObject:nickName forKey:@"nickName"];
     [userDefaults setObject:iconUrl forKey:@"iconUrl"];
     [userDefaults setObject:emailString forKey:@"emailString"];
     */
    
    NSString * floatProfit = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"floatProfit"]];
    NSString * canUseMoney = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"canUseMoney"]];
    NSString * clearMoney = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"clearMoney"]];
    NSString * iconUrl = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"iconUrl"]];
    NSString * nickName = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"nickNameString"]];
    self.phoneString = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"phone"]];
    
    
    self.myView.moneyString = clearMoney;
    self.myView.userMoneyString = canUseMoney;
    self.myView.iconImageString = iconUrl;
    self.myView.nameString = nickName;
    self.myView.loseOrWinString = floatProfit;
    
    [self setupDownTimer];
}


- (void)setupDownTimer{
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown == 0){
        
        [_countDownTimer invalidate];
        
        [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSDictionary * dict = responseObject[@"param"];
            
            //账户余额
            float balanceFloat = [dict[@"balance"] floatValue];
            //浮动盈亏
            NSString * floatProfitString;
            float floatProfit = [dict[@"floatProfit"] floatValue];
            
            if (floatProfit >= 0) {
                floatProfitString = [NSString stringWithFormat:@"+$%.2f",floatProfit];
            }else{
                
                NSString * floatString = [NSString stringWithFormat:@"%.2f",floatProfit];
                floatString = [floatString substringFromIndex:1];
                
                floatProfitString = [NSString stringWithFormat:@"-$%@",floatString];
            }
            
            //            NSString * floatProfitString = [NSString stringWithFormat:@"%.2f",floatProfit];
            //可用保证金
            float marginFree = [dict[@"marginFree"] floatValue];
            //净值
            float clearMoney = balanceFloat + floatProfit;
            NSString * clearMoneyString = [NSString stringWithFormat:@"$%.2f",clearMoney];
            //可用资金    已用保证金
            
            NSString * canUseMoneyString = [NSString stringWithFormat:@"%.2f",marginFree];
            
            
            
            self.myView.loseOrWinString = floatProfitString;
            self.myView.userMoneyString = canUseMoneyString;
            self.myView.moneyString = clearMoneyString;
            
            secondsCountDown = 2;
            
            [self setupDownTimer];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];
        
        
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    
//    [self loadData];
    
    self.view.userInteractionEnabled = YES;
    
    _showStringArray = @[@"出金",@"入金",@"实名认证",@"银行卡",@"手机号"];
    _imageNameArray = @[@"出金",@"入金2",@"实名认证",@"银行卡",@"手机号2"];
    
    [self setupNavBar];
    [self setupUI];
}



- (void)setupNavBar{
    
    self.title = @"我的账户";
    
    UIButton * nextButton = [[UIButton alloc] init];
    
    nextButton.frame = CGRectMake(0 * SCREENH6, 0 * SCREENH6, 55 * SCREENH6, 25 * SCREENH6);
    nextButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    [nextButton setImage:[UIImage imageNamed:@"明细"] forState:UIControlStateNormal];
    [nextButton setTitle:@"明细" forState:UIControlStateNormal];
    
    [nextButton addTarget:self action:@selector(pushToInformationVC) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithCustomView:nextButton];
    
    self.navigationItem.rightBarButtonItem = rightButton;
    
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToMySelfVC) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    self.myView = [[MyAccountView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 248 * SCREENH6)];
    
    [self.view addSubview:self.myView];
    
    CGFloat y = CGRectGetMaxY(self.myView.frame);
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, y,SCREEN_WIDTH ,SCREENH_HEIGHT - y)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"背景"]];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[MySelfTableViewCell class] forCellReuseIdentifier:@"myselfCell"];
    
    [self.view addSubview:self.tableView];
    
    self.cardView = [UIView new];
    
    self.cardView.hidden = YES;
    self.cardView.layer.cornerRadius = 15 * SCREENH6;
    self.cardView.backgroundColor = ColorWithRGB(0xe8e8e8);
    self.cardView.userInteractionEnabled = YES;
    
    self.cardView.layer.masksToBounds = YES;
    
    [self.view addSubview:self.cardView];
    
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view);
        make.width.mas_equalTo(273 * SCREENH6);
        make.height.mas_equalTo(163 * SCREENH6);
    }];
    
    UIImageView * topImageView = [[UIImageView alloc] init];
    
    //    132*115
    topImageView.image = [UIImage imageNamed:@"请先绑定银行卡"];
    
    self.topImageView = topImageView;
    self.topImageView.hidden = YES;
    
    [self.view addSubview:self.topImageView];
    
    UILabel * showLabel = [UILabel new];
    
    showLabel.text = @"请先绑定银行卡";
    showLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    showLabel.textColor = ColorWithRGB(0x333333);
    
    self.showLabel = showLabel;
    
    [self.cardView addSubview:self.showLabel];
    
    UIView * lineView = [[UIView alloc] init];
    
    lineView.backgroundColor = ColorWithRGB(0xbebebe);
    
    self.lineView = lineView;
    
    [self.cardView addSubview:self.lineView];
    
    
    UILabel * backLabel = [UILabel new];
    
    backLabel.text = @"返回";
    backLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    backLabel.textColor = ColorWithRGB(0x979797);
    backLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapBack = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackAction)];
    [backLabel addGestureRecognizer:tapBack];
    
    self.backLabel = backLabel;
    
    [self.cardView addSubview:self.backLabel];
    
    UIView * lineView2 = [[UIView alloc] init];
    
    lineView2.backgroundColor = ColorWithRGB(0xbebebe);
    
    self.lineView2 = lineView2;
    
    [self.cardView addSubview:self.lineView2];
    
    
    UILabel * sureLabel = [UILabel new];
    
    sureLabel.text = @"确定";
    sureLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sureLabel.textColor = ColorWithRGB(0xed4444);
    sureLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapSure = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSureAction)];
    [sureLabel addGestureRecognizer:tapSure];
    
    self.sureLabel = sureLabel;
    
    [self.cardView addSubview:self.sureLabel];
    
    
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.cardView);
        make.height.mas_equalTo(115 * SCREENH6);
        make.width.mas_equalTo(132 * SCREENH6);
        make.top.mas_equalTo(self.cardView.mas_top).offset(-65 * SCREENH6);
    }];
    
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topImageView.mas_bottom).offset(20 * SCREENH6);
        make.centerX.mas_equalTo(self.cardView);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.cardView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.showLabel.mas_bottom).offset(25 * SCREENH6);
    }];
    
    
    [self.backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.cardView).offset(55 * SCREENH6);//50
        make.bottom.mas_equalTo(self.cardView).offset(-12 * SCREENH6);//20
    }];
    
    [self.lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lineView.mas_bottom);
        make.bottom.mas_equalTo(self.cardView);
        make.width.mas_equalTo(1);
        make.centerX.mas_equalTo(self.cardView);
    }];
    
    [self.sureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backLabel);
        make.trailing.mas_equalTo(self.cardView.mas_trailing).offset(-55 * SCREENH6);
    }];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 5;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MySelfTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myselfCell" forIndexPath:indexPath];
    
    cell.explationLabel.text = self.showStringArray[indexPath.row];
    cell.iconImage.image = [UIImage imageNamed:self.imageNameArray[indexPath.row]];
    
    if (indexPath.row == 4) {
        cell.phoneNumberLabel.text = self.phoneString;
        cell.rightView.image = [UIImage imageNamed:@""];
    }else{
        cell.phoneNumberLabel.text = @"";
        cell.rightView.image = [UIImage imageNamed:@"修改头像"];
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 60 * SCREENH6;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    
    if (indexPath.row == 0) {
        
        if ([self.showViewString isEqualToString:@"show"]) {
            
            self.cardView.hidden = NO;
            self.topImageView.hidden = NO;
            
        }else{
            
            GetMoneyViewController * cardVC = [GetMoneyViewController new];
            cardVC.useMoney = self.myView.userMoneyString;
            
            [self.navigationController pushViewController:cardVC animated:YES];
            
        }
    }else if (indexPath.row == 1){
        
//        if ([self.showViewString isEqualToString:@"show"]) {
//            
//            self.cardView.hidden = NO;
//            self.topImageView.hidden = NO;
//            
//        }else{
        
        PayViewController * payVC = [PayViewController new];
        
        [self.navigationController pushViewController:payVC animated:YES];
            
//        }
    }else if (indexPath.row == 2){
        
        VeriftyViewController * veriftyVC = [VeriftyViewController new];
        
        [self.navigationController pushViewController:veriftyVC animated:YES];
    }else if (indexPath.row == 3){
        
        AddBankCardViewController * addVC = [AddBankCardViewController new];
        
        [self.navigationController pushViewController:addVC animated:YES];
    }
    
    
    
    
    
}


//轻拍手势的回调方法
- (void)tapBackAction{
    
    self.cardView.hidden = YES;
    self.topImageView.hidden = YES;
    
}

- (void)tapSureAction{
    
    self.cardView.hidden = YES;
    self.topImageView.hidden = YES;
    
    MoneyCardViewController * cardVC = [MoneyCardViewController new];
    
    [self.navigationController pushViewController:cardVC animated:YES];
}

- (void)backToMySelfVC{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)pushToInformationVC{
    
    self.hidesBottomBarWhenPushed = YES;
    
    DetailViewController * detailVC = [DetailViewController new];
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [_countDownTimer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
